package com.whyvent.config;

import com.whyvent.entity.MUser;
import com.whyvent.service.IMBlogService;
import com.whyvent.service.IMUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * @author WhyVent
 */
//@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    IMUserService userService;

    /**
     * 授权
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 首页所有人可以访问，功能页只有对应有权限的人才能访问
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                /*.antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3")*/;

        // 没有权限默认会到登录页面，需要开启登录的页面，并定制登录页
//        http.formLogin().loginPage("/toLogin");

        // 开启记住我功能，存入cookie，默认保存两周，并自定义接收前端的参数
//        http.rememberMe().rememberMeParameter("remember");

        // 关闭csrf功能，登录失败可能存在的原因
        // http.csrf().disable();

        // 注销，开启了注销功能，并跳到首页
//        http.logout().logoutSuccessUrl("/");
    }

    /**
     * 认证
     * 注意密码编码：PasswordEncoder
     * 在SpringSecurity 5.0+新增了很多的加密方法
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 这些数据正常应该从数据库中读
//        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
//                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
//                .and().withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
//                .and().withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");

//        auth.userDetailsService(userService);
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
